package com.wensi.lib_voice.wakeup

import android.content.Context
import android.util.Log
import com.baidu.speech.EventListener
import com.baidu.speech.EventManager
import com.baidu.speech.EventManagerFactory
import com.baidu.speech.asr.SpeechConstant.*
import org.json.JSONObject

/**
 * 语音唤醒：小爱同学
 */
object VoiceWakeup {
    private lateinit var wakeupJson: String
    private lateinit var wp: EventManager

    // 初始化唤醒
    fun initWakeup (context: Context, listener: EventListener) {
        val map = HashMap<Any, Any>()
        // 本地文件的路径
        /**
         * 2021-07-07 14:57:36.004 32696-32696/com.wensi.module_developer W/System.err: org.json.JSONException: No value for appid
         * 2021-07-07 14:57:36.004 32696-32696/com.wensi.module_developer W/System.err:     at org.json.JSONObject.get(JSONObject.java:399)
         * 2021-07-07 14:57:36.004 32696-32696/com.wensi.module_developer W/System.err:     at org.json.JSONObject.getInt(JSONObject.java:488)
         *
         * 2021-07-07 14:57:35.999 32696-32696/com.wensi.module_developer I/VoiceManager: 开始唤醒
         * 2021-07-07 14:57:35.999 32696-32696/com.wensi.module_developer I/VoiceManager: {"kws-file":"assets:\/\/\/wakeup.bin","accept-audio-volume":false}
         * 2021-07-07 14:57:36.005 32696-32696/com.wensi.module_developer W/System.err:     at com.wensi.lib_voice.manager.VoiceManager.startWakeup(VoiceManager.kt:69)
         * 2021-07-07 14:57:36.022 32696-32696/com.wensi.module_developer W/System.err:     at com.wensi.lib_voice.manager.VoiceManager.startWakeup(VoiceManager.kt:69)
         * 2021-07-07 14:57:36.036 32696-32696/com.wensi.module_developer I/VoiceManager: event: name=wp.error, params={"error":11,"desc":"Wakeup exception","sub_error":11004}
         * 针对上面报错：只需要修改wakeup.bin --->>> mywakeup.bin 即可，即使仍然有"No value for appid"报错，也不妨碍使用
         */
        map[WP_WORDS_FILE] = "assets:///mywakeup.bin"
        // 是否获取音量
        map[ACCEPT_AUDIO_VOLUME] = false
        // 转换成json
        wakeupJson = JSONObject(map as Map<Any, Any>).toString()
        // 设置初始化监听
        //this是Activity或其它Context类
        wp = EventManagerFactory.create(context, "wp")
        wp.registerListener(listener)

        startWakeup()
    }

    // 启动唤醒
    fun startWakeup() {
        Log.i("VoiceManager", wakeupJson)
        wp.send(WAKEUP_START, wakeupJson, null , 0, 0)
    }

    // 停止唤醒
    fun stopWakeup() {
        wp.send(WAKEUP_STOP, null, null, 0, 0)
    }
}